package com.xtc.netty.protocol.http.xml;

import com.xtc.netty.protocol.http.model.Order;
import com.xtc.netty.protocol.http.xml.codec.HttpXmlRequestEncoder;
import com.xtc.netty.protocol.http.xml.codec.HttpXmlResponseDecoder;
import com.xtc.netty.protocol.http.xml.handler.HttpXmlClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;

import java.net.InetSocketAddress;

/**
 * @author Administrator
 */
public class HttpXmlClient {

    private int port;

    public HttpXmlClient(int port) {
        this.port = port;
    }

    public void connect() {
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            Bootstrap client = new Bootstrap();
            client.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("http-decoder", new HttpResponseDecoder())
                                    .addLast("http-aggregator", new HttpObjectAggregator(65536))
                                    .addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true))
                                    .addLast("http-encoder", new HttpRequestEncoder())
                                    .addLast("xml-encoder", new HttpXmlRequestEncoder())
                                    .addLast("xmlClientHandler", new HttpXmlClientHandler());
                        }
                    });
            ChannelFuture future = client.connect(new InetSocketAddress(this.port)).sync();

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new HttpXmlClient( 9090).connect();
    }
}
